using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Framework.Serialization;
using System.Collections.Generic;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class GameplayAreaModularConfigMgr : Singleton<GameplayAreaModularConfigMgr>
    {
        private const int CacheSize = 5;

        /// <summary>
        /// 模块化配置的缓存，玩家频繁切换地图时作用最大
        /// </summary>
        private Dictionary<string, ISerializeByteBuf> _mcCache = new(CacheSize);
        private Queue<string> _pathQueue = new(CacheSize);

        private GameplayAreaModularConfigMgr()
        {

        }

        public async UniTask<T> LoadModularConfig<T>(string cfgPath, ResLoader customLoader = null) where T : ISerializeByteBuf, new()
        {
            ISerializeByteBuf c = null;
            //缓存里拿不到就加载
            if (!_mcCache.TryGetValue(cfgPath, out c))
            {
                ResLoader resLoader = customLoader ?? ResLoader.Create();
                var packText = await resLoader.LoadABAssetAwait<TextAsset>(cfgPath);
                if (packText == null)
                {
                    LogGame.LogError($"读取模块化配置失败。Path {cfgPath}");
                    return default;
                }
                ByteBuf buf = new ByteBuf(packText.bytes);
                c = buf.DeSerializeObject<T>();

                if (customLoader == null)
                {
                    resLoader.Put2Pool();
                }

                //如果缓存超限，就移除最早的一个
                if (_pathQueue.Count == CacheSize)
                {
                    string earliestPath = _pathQueue.Dequeue();
                    _mcCache.Remove(earliestPath);
                }

                //加入缓存
                _mcCache.Add(cfgPath, c);
                _pathQueue.Enqueue(cfgPath);
            }
            if (c is IModularConfig mc)
            {
                mc.Init();
            }
            return (T)c;
        }
    }
}
